<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <div class="title">
          <img src="@/assets/logo.png" alt="">
        </div>
        <h3 class="title">科研管理系统登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="Username"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="Password"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登录</el-button>

    </el-form>
  </div>
</template>

<script>
// import { validUsername } from '@/utils/validate'
import { ssoUserInfo } from '@/api/user'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      // if (!validUsername(value)) {
      //   callback(new Error('Please enter the correct user name'))
      // } else {
      //   callback()
      // }
      if (value.length < 5) {
        callback(new Error('The username can not be less than 5 digits'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('The password can not be less than 5 digits'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    this.performSSOLogin()
  },
  methods: {

    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            // 使用replace方式跳转，确保清除URL中的token参数
            this.$router.replace({ path: this.redirect || '/' })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.$message.error('error submit!!')
          return false
        }
      })
    },
    // 执行SSO登录
    performSSOLogin() {
      console.log('performSSOLogin')
      this.loading = true
      // 1. 首先检查URL中是否有token参数（如：http://xkygl.hbnu.edu.cn/?token=xxx#/ssoLogin?redirect=%2Fdashboard）
      const urlParams = new URLSearchParams(window.location.search)
      const tokenFromUrl = urlParams.get('token')
      if (tokenFromUrl) {
        // 如果URL中有token，直接使用token登录
        console.log('从URL获取到token，使用token登录')
        this.$store.dispatch('user/loginBySSO', tokenFromUrl).then(() => {
          // 使用replace方式跳转，清除URL中的token参数
          this.$router.replace({ path: this.redirect || '/' })
          this.loading = false
        }).catch(error => {
          console.error('token登录失败:', error)
          this.loading = false
          // token登录失败，继续尝试其他登录方式
          this.trySSOLoginFlow()
        })
      } else {
        // URL中没有token，尝试SSO接口登录
        this.trySSOLoginFlow()
      }
    },

    // 尝试SSO接口登录流程
    trySSOLoginFlow() {
      ssoUserInfo().then(response => {
        if (response.code === 200) {
          // 接口返回200，使用返回的token登录
          const { token } = response.data
          this.$store.dispatch('user/loginBySSO', token).then(() => {
            // 使用replace方式跳转，确保清除URL中的token参数
            this.$router.replace({ path: this.redirect || '/' })
          })
        } else {
          // 接口返回非200，进入重定向到CAS登录页面的逻辑
          this.redirectToCasLogin()
        }
      }).catch(error => {
        // 接口调用失败，进入重定向到CAS登录页面的逻辑
        console.error('SSO接口调用失败:', error)
        this.redirectToCasLogin()
      })
    },

    // 重定向到CAS登录页面
    redirectToCasLogin() {
      // https://authserver.hbnu.edu.cn/authserver/login?service=http://xkygl.hbnu.edu.cn/
      const url = 'https://authserver.hbnu.edu.cn/authserver/login?service=http://xkygl.hbnu.edu.cn:9528/sso/checkTicket'
      const link = document.createElement('a')
      link.href = url
      link.rel = 'noreferrer'
      link.click()
      this.loading = false
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
